package com.ts.proj.json;

import com.ts.base.controller.BaseController;
import com.ts.common.constant.ConsoleConstant;
import com.ts.common.constant.Controller2FTLConstant;
import com.ts.common.constant.ProjectStateConstant;
import com.ts.proj.entity.FileEntity;
import com.ts.proj.entity.ProjectEntity;
import com.ts.proj.entity.ProjectMeetingEntity;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.proj.service.FileService;
import com.ts.proj.service.ProjectMeetingService;
import com.ts.proj.service.ProjectService;
import com.ts.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;


@RestController
public class ProjectTouHouJson extends BaseController {

    @Autowired
    private ProjectMeetingService projectMeetingService;

    @Autowired
    private ProjectService projectService;

    @Autowired
    private FileService fileService;

    @Value("${upload.location-pre}")
    private String locaionPre ;

    @Value("${upload.split}")
    private String split;

    @RequestMapping(value = "/project-meet-list/{page}/{size}/{id}")
    public Map<String ,Object> meetingProject(@PathVariable("page") Integer page, @PathVariable("size") Integer size,@PathVariable("id") Integer id){
        HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        PageData pageData = this.getPageData();
        pageData.put("deleteFlag", "N");
        pageData.put("proId", id);
        long count = projectMeetingService.count(pageData);
        List<ProjectMeetingEntity> projects = projectMeetingService.findAll(pageData,page-1,size);
        pageData.put("total",count);
        pageData.put("rows", projects);
        return pageData;
    }

    @RequestMapping(value = "/meet-ins-upd-del")
    public Object logCreateUpdate(){
        PageData pageData = this.getPageData();
        SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
        if(null!=pageData.get("id")&&!"".equals(pageData.get("id").toString())){
            Integer id = -1;
            //修改
            if(null!=pageData.get("id")&&!"".equals(pageData.get("id").toString())){
                id = Integer.valueOf(pageData.get("id").toString());
            }
            ProjectMeetingEntity projectMeetingEntity = null;
            projectMeetingEntity = projectMeetingService.findById(id);

            ProjectEntity projectEntity = projectService.findById(projectMeetingEntity.getProId());
            //删除
            if(null!=pageData.get("deleteflag")&&!"".equals(pageData.get("deleteflag").toString())){

                //根据file的doc_type可以查出所有相关联file（th_zt_meet_[meetid]）
                PageData pageData1 = new PageData();
                pageData1.put("deleteFlag", "N");
                pageData1.put("docType", "th_zt_meet_"+projectMeetingEntity.getId());
                List<FileEntity> fileEntityList = fileService.findAll(pageData1);
                for(FileEntity fileEntity : fileEntityList) {
                    String path = locaionPre;
                    path += projectEntity.getUuid() + split + fileEntity.getState()
                            + split + fileEntity.getState() + "_" + fileEntity.getProjName();
                    fileEntity.setDeleteFlag("Y");
                    fileService.save(fileEntity);
                    File localFile = new File(path);
                    localFile.delete();
                }
                projectMeetingEntity.setDeleteFlag(pageData.get("deleteflag").toString());
            }
            if(null!=pageData.get("meetName")&&!"".equals(pageData.get("meetName").toString())){
                projectMeetingEntity.setMeetName(pageData.get("meetName").toString());
            }
            if(null!=pageData.get("meetTime")&&!"".equals(pageData.get("meetTime").toString())){
                projectMeetingEntity.setMeetTime(pageData.get("meetTime").toString());
            }
            if(null!=pageData.get("meetBrief")&&!"".equals(pageData.get("meetBrief").toString())){
                projectMeetingEntity.setMeetBrief(pageData.get("meetBrief").toString());

            }
            if(null!=pageData.get("proId")&&!"".equals(pageData.get("proId").toString())){
                projectMeetingEntity.setProId(Integer.valueOf(pageData.get("proId").toString()));
            }
            projectMeetingEntity.setUserId(systemUserEntity.getId());
            projectMeetingEntity.setBelongTo(systemUserEntity.getBelongTo());
            projectMeetingService.save(projectMeetingEntity);
        }
        return "success";
    }

//    @RequestMapping("/expert-upload-json/{id}")
//    public String inport(@RequestParam("file") MultipartFile file,@PathVariable("id") Integer id){
//        if (file.isEmpty()) {
//            return "上传失败，请选择文件";
//        }
//        try {
//            ProjectEntity byId = projectService.findById(id);
//            String fileName = byId.getId()+"_"+"会议资料"+"_"+byId.getProName()+"_"+file.getOriginalFilename();
//            String fileFolder = Controller2FTLConstant.WINDOWPATH + Controller2FTLConstant.FILEABSTRACTPATH + byId.getProId() + Controller2FTLConstant.WINDOWSPLIT + "touhou" + Controller2FTLConstant.WINDOWSPLIT;;
//            File folder = new File(fileFolder);
//            if(!folder.exists()){
//                folder.mkdirs();
//            }
//            File dest = new File(fileFolder + fileName);
//            file.transferTo(dest);
//            //记入数据库
//            FileEntity fileEntity = new FileEntity();
//
//            HttpSession session = this.getRequest().getSession();
//            SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
//            fileEntity.setUserId(user.getId());
//            fileEntity.setBelongTo(user.getBelongTo());
//            fileEntity.setFileName(dest.getName());
//            fileEntity.setState(byId.getProLocation());
//            fileEntity.setProjId(byId.getProId());
//            fileEntity.setProjName(byId.getProName());
//            fileService.save(fileEntity);
//            return "Success";
//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//        }
//        return "Fail！";
//    }

    @RequestMapping("/project-meet-count/{id}")
    public long projectMeetCount(@PathVariable("id") Integer id){
        PageData pd = new PageData();
        pd.put("deleteFlag", "N");
        pd.put("proId", id);
        return projectMeetingService.count(pd);
    }

    @RequestMapping(value = "/project-tuichu-iud/{id}")
    public Object projTuichuUpdate(@PathVariable("id") Integer id){
        PageData pageData = this.getPageData();
        SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        String proOutMoney = pageData.getString("proOutMoney");
        String proOutWay = pageData.getString("proOutWay");
        String content = pageData.getString("content");

        ProjectEntity projectEntity = projectService.findById(id);
        projectEntity.setProOutMoney(proOutMoney);
        projectEntity.setProOutWay(proOutWay);
        projectEntity.setProOutContent(content);
        projectEntity.setUserId(systemUserEntity.getId());
        projectEntity.setBelongTo(systemUserEntity.getBelongTo());
        projectEntity.setProTuichuFlag(1);

        projectService.save(projectEntity);
        return null;
    }
}
